#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tornado.ioloop
import tornado.web
import tornado.options
from tornado.options import define, options
import os
import sys

# 添加当前目录到 Python 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from handlers import MainHandler, ApiHandler, HealthHandler, CalcHandler
from config import settings

define("port", default=8888, help="run on the given port", type=int)
define("debug", default=True, help="run in debug mode", type=bool)


class Application(tornado.web.Application):
    """主应用类"""
    
    def __init__(self):
        # 定义路由
        handlers = [
            (r"/", MainHandler),
            (r"/api/hello", ApiHandler),
            (r"/health", HealthHandler),
            (r"/api/calc", CalcHandler),
        ]
        
        # 应用设置
        app_settings = {
            "template_path": os.path.join(os.path.dirname(__file__), "templates"),
            "static_path": os.path.join(os.path.dirname(__file__), "static"),
            "debug": options.debug,
            "cookie_secret": "your-secret-key-change-this-in-production",
            "xsrf_cookies": True,
        }
        
        super(Application, self).__init__(handlers, **app_settings)


def main():
    """主函数"""
    tornado.options.parse_command_line()
    
    app = Application()
    
    print(f"Starting server on port {options.port}")
    print(f"Debug mode: {options.debug}")
    print(f"Visit: http://localhost:{options.port}")
    
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
    main()
